package com.cz.nongyetongv5.activity;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.adapter.DaiShangChuanListAdapter;
import com.cz.nongyetongv5.adapter.config.CommonConstants;
import com.cz.nongyetongv5.adapter.dao.DatabaseHelper;
import com.cz.nongyetongv5.bean.BeiJianDanWei;
import com.cz.nongyetongv5.bean.ChanPinJianCeRecord;
import com.cz.nongyetongv5.bean.HttpBack;
import com.cz.nongyetongv5.bean.JianChaRenYuan;
import com.cz.nongyetongv5.bean.Photo;
import com.cz.nongyetongv5.bean.User;
import com.cz.nongyetongv5.bean.YangPin;
import com.cz.nongyetongv5.custom.dialog.CustomDialog;
import com.cz.nongyetongv5.task.UploadPlanTask;
import com.cz.nongyetongv5.utils.Conf;
import com.cz.nongyetongv5.utils.ConfigUtil;
import com.cz.nongyetongv5.utils.HttpUtilsEx;
import com.cz.nongyetongv5.utils.SerliazableUtil;
import com.google.gson.Gson;

public class ChanPinJianCeUploadActivity extends Fragment implements
        OnClickListener {

    /**
     * 待上传的ListView
     */
    private ListView lvListView = null;

    /**
     * 数据库工具
     */
    private DatabaseHelper db = null;

    private User user = null;

    private ConfigUtil configUtil = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.jiandujiancha_daishangchuan,
                container, false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);

        configUtil = new ConfigUtil(getResources());
        initView();

        initConfig();

    }

    /**
     * 初始化视图
     */
    private void initView() {
        lvListView = (ListView) getActivity().findViewById(
                R.id.lvJianDuJianChaDaiShangChuanList);

    }

    /**
     * 舒适化数据配置
     */
    private void initConfig() {

        this.db = new DatabaseHelper(getActivity(), CommonConstants.DBNAME,
                null, CommonConstants.DATABASE_VERSION);

        this.user = (User) getActivity().getIntent().getSerializableExtra(
                "user");
        reloadData();
    }

    /**
     * 刷新数据
     */
    List<ChanPinJianCeRecord> chanPinJianCeRecords = null;

    public void reloadData() {
        chanPinJianCeRecords = SerliazableUtil
                .getChanPinJianCeRecordByState(1, this.user.getUsername());

        Log.d("debugsize", String.valueOf(chanPinJianCeRecords.size()));

        new Thread(new Runnable() {

            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }

        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                //                for (ChanPinJianCeRecord record :
                //                        chanPinJianCeRecords) {
                //                    System.out.println(record.toString());
                //                }
                DaiShangChuanListAdapter adpJianDuJianChaListAdapter = new DaiShangChuanListAdapter(
                        getActivity(), chanPinJianCeRecords, ChanPinJianCeUploadActivity.this);
                lvListView.setAdapter(adpJianDuJianChaListAdapter);
            }
        }
    };

    @Override
    public void onClick(View v) {

        if (v instanceof Button) {

            if (v.getId() == R.id.btnDaiShangChuanDelete) {

                if (v.getTag() != null && v.getTag() instanceof Integer) {

                    final int position = (Integer) v.getTag();

                    final CustomDialog deleteDaiShangChuanDialog = new CustomDialog(
                            getActivity());

                    deleteDaiShangChuanDialog
                            .setOnCancleClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteDaiShangChuanDialog.dismiss();
                                }
                            });

                    // 当点击确定的时候
                    deleteDaiShangChuanDialog
                            .setOnActionClickListener(new OnClickListener() {

                                @Override
                                public void onClick(View v) {

                                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvListView
                                            .getAdapter();

                                    if (adpJianDuJianChaListAdapter
                                            .getItem(position) != null
                                            && adpJianDuJianChaListAdapter
                                            .getItem(position) instanceof ChanPinJianCeRecord) {

                                        ChanPinJianCeRecord chanPinJianCeRecord = (ChanPinJianCeRecord) adpJianDuJianChaListAdapter
                                                .getItem(position);

                                        SerliazableUtil
                                                .deleteChanPinJianCe(chanPinJianCeRecord
                                                        .getFileId());

                                        // 删除
                                        adpJianDuJianChaListAdapter
                                                .remove(position);

                                        deleteDaiShangChuanDialog.dismiss();

                                        Toast.makeText(getActivity(), "删除成功!",
                                                Toast.LENGTH_SHORT).show();
                                    }

                                }
                            });

                    deleteDaiShangChuanDialog.setMessage(getActivity()
                            .getResources().getString(
                                    R.string.delete_daishangchuan_message));

                    deleteDaiShangChuanDialog.setCancleTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_cancle));

                    deleteDaiShangChuanDialog.setActionTxt(getActivity()
                            .getString(R.string.jiandujiancha_item_sure));

                    deleteDaiShangChuanDialog.show();
                }
            }

            if (v.getId() == R.id.btnDaiShangChuanEdit) {

                final int position = (Integer) v.getTag();

                if (getActivity() instanceof ChanPinJianCeActivity) {

                    ChanPinJianCeActivity activity = (ChanPinJianCeActivity) getActivity();

                    DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvListView
                            .getAdapter();

                    if (adpJianDuJianChaListAdapter.getItem(position) != null
                            && adpJianDuJianChaListAdapter.getItem(position) instanceof ChanPinJianCeRecord) {

                        ChanPinJianCeRecord record = (ChanPinJianCeRecord) adpJianDuJianChaListAdapter
                                .getItem(position);

                        record.setState(1);

                        activity.toEdit(record);

                    }

                }

            }

            if (v.getId() == R.id.btnDaiShangChuanUpload) {

                //				if (user.isTester()) {
                //
                //					DialogUtil.showMessageDialog("演示账户禁止上传..", null,
                //							getActivity());
                //
                //					return;
                //				}

                int position = (Integer) v.getTag();

                // 获得每一项的跟布局
                m_itemView = lvListView.getChildAt(position);

                DaiShangChuanListAdapter adpJianDuJianChaListAdapter = (DaiShangChuanListAdapter) lvListView
                        .getAdapter();

                if (adpJianDuJianChaListAdapter.getItem(position) != null) {

                    m_record = (ChanPinJianCeRecord) adpJianDuJianChaListAdapter
                            .getItem(position);

                    // final String sign  = ImageUtil.bitToBase64FromFile(record.getQianMingPath());

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            HttpUtilsEx ex = new HttpUtilsEx();
                            String uploadurl = Conf.v1609_file;//getResources().getString(R.string.upload_upload);
                            HttpBack data = ex.sendRequestPic_v1609(uploadurl, m_record.getQianMingPath());
                            //                            data.setCode(400);
                            if (data.getCode() == 200) {
                                try {
                                    JSONObject pjson = new JSONObject(data.getData());
                                    //                                    m_signdata = pjson.getJSONObject("a").getString("url");
                                    m_signdata = pjson.optJSONObject("msg").optString("url");
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                    //return;
                                }
                            } else {
                                //return;
                            }
                            JSONArray photos = new JSONArray();
                            for (Photo photo : m_record.getUploadPhoto()) {
                                if (photo.isUpload()) {
                                    HttpBack picdatac = ex.sendRequestPic_v1609(uploadurl, photo.getBigPhotoPath());
                                    //                                    picdatac.setCode(400);
                                    if (picdatac.getCode() == 200) {
                                        try {
                                            JSONObject photoJsonObj = new JSONObject();
                                            JSONObject pjson = new JSONObject(picdatac.getData());
                                            photoJsonObj.put("url", pjson.optJSONObject("msg").optString("url"));
                                            photoJsonObj.put("comment", photo.getComment());
                                            photoJsonObj.put("time", photo.getPhotoTime());
                                            photoJsonObj.put("position",
                                                    photo.getAddressDesc());
                                            photoJsonObj.put("longitude",
                                                    Double.isNaN(photo.getLongitude()) ? 0.00 : photo.getLongitude());
                                            photoJsonObj.put("latitude",
                                                    Double.isNaN(photo.getLatitude()) ? 0.00 : photo.getLatitude());
                                            photos.put(photoJsonObj);
                                        } catch (JSONException e) {
                                            // TODO Auto-generated catch block
                                            e.printStackTrace();
                                        }
                                    }
                                }
                            }
                            m_photos = photos;
                            Log.d("data", String.valueOf(m_photos));
                            m_samples = new JSONArray();
                            for (YangPin item : m_record.getYangPins()) {
                                try {
                                    JSONObject ypObj = new JSONObject();
                                    ypObj.put("sample_no", item.getBianHao().getBianHaoString());
                                    ypObj.put("sample_name", item.getName());
                                    ypObj.put("breed_id", item.getBreedId());
                                    ypObj.put("sample_amount", item.getJiShu());
                                    ypObj.put("sample_place", checkEmpty(item.getLocale()));
                                    ypObj.put("sample_source", checkEmpty(item.getSource()));
                                    ypObj.put("sample_remark", checkEmpty(item.getXingHao()));
                                    Photo pt = item.getUploadPhoto();
                                    if (pt != null) {
                                        HttpBack picdatac2 = ex.sendRequestPic_v1609(uploadurl, pt.getBigPhotoPath());
                                        if (picdatac2.getCode() == 200) {
                                            if (picdatac2.getData() != null) {
                                                JSONObject pjson = new JSONObject(picdatac2.getData());
                                                ypObj.put("photo_url", pjson.optJSONObject("msg").optString("url"));
                                                ypObj.put("photo_comment", checkEmpty(pt.getComment()));
                                                ypObj.put("photo_time", checkEmpty(pt.getPhotoTime()));
                                                ypObj.put("photo_position", checkEmpty(pt.getAddressDesc()));
                                                ypObj.put("photo_longitude", Double.isNaN(pt.getLongitude()) ? 0.00 : pt.getLongitude());
                                                ypObj.put("photo_latitude", Double.isNaN(pt.getLatitude()) ? 0.00 : pt.getLatitude());
                                            }
                                        }
                                    }
                                    m_samples.put(ypObj);
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }
                            }
                            //                            System.out.println(new Gson().toJson(m_samples) + "ppppp");
                            Log.d("debug", String.valueOf(m_samples));
                            uploadHandler.sendEmptyMessage(100);


                        }
                    }).start();
                    //

                } else {
                    Log.d("debug", "不是有效数据");

                }

            }

        }

    }

    private Handler uploadHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            if (msg.what == 100)
                updata(m_record, m_itemView, m_photos, m_signdata, m_samples);
        }
    };


    ChanPinJianCeRecord m_record = null;
    View m_itemView = null;
    String m_signdata = "";
    JSONArray m_photos = new JSONArray();
    JSONArray m_samples = new JSONArray();

    private void updata(ChanPinJianCeRecord record, View itemView, JSONArray photos, String qianMingBase64, JSONArray samples) {


        // 上传地址
        String uploadUrl = Conf.v1609_presample + "PostSamplingRecord";
        Log.d("params_url", uploadUrl);
        JSONObject planJSON = new JSONObject();
        try {
            planJSON.put("user", user.getUsername());
            planJSON.put("region", record.getKnowTown().getCode());

            if (record.getPlan() != null) {
                planJSON.put("task_id", record.getPlan().getId());
            } else {
                planJSON.put("task_id", "0");
            }
            if (record.getRenWuLaiYuan() == null
                    || record.getRenWuLaiYuan().getId() == null) {
                planJSON.put("source", "");
            } else {
                planJSON.put("source", record
                        .getRenWuLaiYuan().getId());
            }
            if (record.getJianCeLeiBie() == null
                    || record.getJianCeLeiBie().getId() == null) {
                planJSON.put("category", "");
            } else {
                planJSON.put("category", record
                        .getJianCeLeiBie().getId());
            }
            planJSON.put("sample_date", record.getTime());

            if (record.getChouYanJiGou() != null) {
                planJSON.put("trusts_id", record.getChouYanJiGou().getId());
                planJSON.put("trusts_name", checkEmpty(record.getChouYanJiGou().getName()));
                planJSON.put("trusts_tel", checkEmpty(record.getChouYanJiGou().getTel()));

            }

            String renYunIds = "";
            String renNames = "";
            for (JianChaRenYuan jianChaRenYuan : record
                    .getChouYangRenYuans()) {
                renYunIds += jianChaRenYuan.getId() + ",";
                renNames += jianChaRenYuan.getName() + ",";
            }
            planJSON.put("humen_id", renYunIds.substring(0, renYunIds.length() - 1));
            planJSON.put("humen_name", renNames.substring(0, renNames.length() - 1));

            String area = record.getArea();
            planJSON.put("area", area == null || area.equals("") ? user.getKnowRegion() : area);
            if (record.getHuanjie() == null) {
                planJSON.put("section", 0);
            } else {
                planJSON.put("section", record.getHuanjie().getId());
            }
            planJSON.put("section_type", "");
            BeiJianDanWei b = record.getShouJianDanWei();
            planJSON.put("ent_id", b.getId());
            planJSON.put("ent_name", b.getName());
            planJSON.put("ent_address", checkEmpty(b.getAddress()));
            planJSON.put("ent_charge", checkEmpty(b.getCharge()));
            planJSON.put("ent_contact", checkEmpty(b.getTel()));
            planJSON.put("add_from", 1);
            if (qianMingBase64 != null && !qianMingBase64.equals("")) {
                planJSON.put("add_sign", qianMingBase64);
            } else {
                planJSON.put("add_sign", "");
            }
            planJSON.put("samples", samples);
            planJSON.put("other_photo", photos);

        } catch (JSONException e) {
            e.printStackTrace();
        }
        //        System.out.println(new Gson().toJson(planJSON));
        String xmldata = "<?xml version=\"1.0\" encoding=\"utf-8\"?> " +
                "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
                "<soap:Body>" +
                "<PostSamplingRecord xmlns=\"http://tempuri.org/\">" +
                " <nAddFrom>1</nAddFrom>" +
                "<szAddFirm>android</szAddFirm>" +
                "<nOffset>0</nOffset>" +
                "<nSize>1</nSize>" +
                "<szJsonPara>" + String.valueOf(planJSON) + "</szJsonPara>" +
                "</PostSamplingRecord>" +
                "</soap:Body>" +
                "</soap:Envelope>";
        Log.d("params", xmldata);
        UploadPlanTask task = new UploadPlanTask(itemView, getActivity(),
                record, (DaiShangChuanListAdapter) lvListView.getAdapter(),
                uploadUrl, xmldata);
        // 执行任务
        task.execute();
    }

    private String checkEmpty(String data) {
        if (data == null)
            return "";
        return data;
    }
}
